package com.zkc.zblog.Shiro;

import com.zkc.zblog.entity.ZblogUser;
import com.zkc.zblog.md5.DigestUtil;
import com.zkc.zblog.service.ZblogUserService;
import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {


    @Resource
    ZblogUserService zblogUserService;
    /*
    执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) throws AuthenticationException{
        System.out.println("执行授权逻辑");
        //获取前端输入的用户信息
        ZblogUser zblogUser=(ZblogUser) principalCollection.getPrimaryPrincipal();
        String username=zblogUser.getUcode();
        String pawssd=zblogUser.getUpassword();
        ZblogUser user;
        try {
            //根据前端传过来的数据在数据库中经行查询，
            user= zblogUserService.login(username,pawssd);
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }

        if(user!=null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRole(user.getUcode());  //赋予角色
            info.addStringPermission("*:*:*");  //赋予权限
            return  info;
        }else{
            return null;
        }

    }
    /*
    执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //1.判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        ZblogUser user = null;
        try {
            user = zblogUserService.login(token.getUsername(),new String(token.getPassword()));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }


        ZblogUser temp;
        //处理session
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
        //获取当前已登录的用户session列表
        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
        //当前session列表的个数
        int  allUser= sessions.size();
        for (Session session: sessions){
            Object attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if(attribute==null){
                continue;//结束本次循环
            }
            temp = (ZblogUser) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
            if(token.getUsername().equals(temp.getUcode())) {//判断当前登录的用户是否在线如果在线直接挤掉上一次登录
                allUser--;
                sessionManager.getSessionDAO().delete(session);
            }
        }
        //2 判断密码
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUpassword(), getName());
        return info;
    }









}
